'use client'

import { SendIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { Message } from "@/app/shared/types/message";
import { MCPClient } from "@/app/shared/utils/mcp-client";
import { ChatCompletion } from "openai/resources/chat/completions";
const Chat = () => {

    const [messages, setMessages] = useState<Message[]>([
        {
            role: "assistant",
            content: "你好，欢迎使用北斗网格引擎MCP服务",
        }
    ]);
    
    const [input, setInput] = useState<string>("");
    const [mcpClient, setMcpClient] = useState<MCPClient | null>(null);

    const [toolResult, setToolResult] = useState<string>("");

    useEffect(() => {
        initMcpClient().then(() => {
            console.log("mcp client initialized");
        });
    }, []);

    async function initMcpClient() {
        const mcpClient = new MCPClient();
        await mcpClient.init();
        setMcpClient(mcpClient);
    }


    /**
     * 输入框按下回车键
     * @param e - 键盘事件
     */
    const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === "Enter") {
            handleSend();
        }
    }

    /**
     * 发送消息
     */
    const handleSend = () => {
        if (input.trim() === "") return;
        // 【发送消息】
        const userInput: Message = {
            role: "user",
            content: input,
        }
        setMessages([...messages, userInput]);
        setInput("");

        // 【调用mcp】
        if (mcpClient) {
            mcpClient.processQuery(input).then(async (response) => {
                console.log("mcp client response:", response);
                // [工具调用]
                if ("choices" in response && response.choices && response.choices.length > 0 &&
                    "message" in response.choices[0] && "tool_calls" in response.choices[0].message
                    && response.choices[0].message.tool_calls && response.choices[0].message.tool_calls.length > 0
                ) {
                    const toolCall = response.choices[0].message.tool_calls[0];
                    const toolName = toolCall.function.name;
                    setMessages(prevMessages => [...prevMessages, {
                        role: "tool",
                        content: "调用工具:" + toolName + " 参数:" + toolCall.function.arguments,
                    }]);
                    // 【调用工具】mcp发起远程函数调用
                    const toolArgs = JSON.parse(toolCall.function.arguments);
                    const toolResult = await mcpClient.callTool(toolName, toolArgs)
                    setMessages(prevMessages => [...prevMessages, {
                        role: "tool",
                        content: "工具调用结果:" + JSON.stringify(toolResult),
                    }]);
                    // 【总结工具调用结果】
                    const summary = await mcpClient.processQuery( 
                         "工具调用结果:" + JSON.stringify(toolResult),
                    )
                    if("choices" in summary && summary.choices && summary.choices.length > 0 &&
                        "message" in summary.choices[0] && "content" in summary.choices[0].message
                    ) {
                        setMessages(prevMessages => [...prevMessages, {
                            role: "assistant",
                            content: summary.choices[0].message.content as string,
                        }]);
                    }
                    
                }
                // [普通对话]
                else if("choices" in response && response.choices && response.choices.length > 0) {
                    const mcpResponse: Message = {
                        role: "assistant",
                        content: response.choices[0].message.content as string,
                    }
                    setMessages(prevMessages => [...prevMessages, mcpResponse]);
                }
            })
        }

        // 清理函数
        return () => {
            if (mcpClient) {
                mcpClient.close();
            }
        }
       
    }

    return (
        <div className="flex flex-col h-full max-w-md mx-auto">
            <div className="flex-1 overflow-y-auto p-4 space-y-4">
                {messages.map((message, index) => (
                <div
                    key={index}
                    className={`flex ${message.role === "user" ? "justify-end" : "justify-start"}`}
                >
                    <div
                    className={`rounded-3xl px-4 py-2 max-w-[80%] ${
                        message.role === "user"
                        ? "bg-black text-white"
                        : "bg-gray-100 text-black"
                    }`}
                    >
                    {message.content}
                    </div>
                </div>
                ))}
            </div>
            <div className="border-t p-4">
                <div className="flex items-center rounded-full border bg-white">
                <input
                    type="text"
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    onKeyDown={handleKeyDown}
                    placeholder="Type your message..."
                    className="flex-1 px-4 py-2 bg-transparent outline-none rounded-full"
                />
                <button
                    onClick={handleSend}
                    className="p-2 rounded-full bg-gray-400 mr-1"
                >
                    <SendIcon className="h-5 w-5 text-white" />
                </button>
                </div>
            </div>
        </div>
    )
}

export default Chat;